<template>
  <div>
    <el-select ref="headerSearchSelectRef" v-model="search" :remote-method="querySearch" filterable default-first-option
      remote placeholder="菜单搜索 ：支持菜单名称、路径" class="header-search-select" @change="change">
      <el-option v-for="option in options" :key="option.item.path" :value="option.item"
        :label="option.item.title.join(' > ')" />
    </el-select>
  </div>
</template>

<script setup>
import Fuse from 'fuse.js'
import { isHttp } from '@/utils/validate'
import { usePermissionStore } from '@/store/modules/permission'

const search = ref('');
const options = ref([]);
const searchPool = ref([]);
const fuse = ref(undefined);
const headerSearchSelectRef = ref(null);
const router = useRouter();
const routes = computed(() => usePermissionStore().routes);

function change(val) {
  const path = val.path;
  const query = val.query;
  if (isHttp(path)) {
    // http(s):// 路径新窗口打开
    const pindex = path.indexOf("http");
    window.open(path.substr(pindex, path.length), "_blank");
  } else {
    if (query) {
      router.push({ path: path, query: JSON.parse(query) });
    } else {
      router.push(path)
    }
  }

  search.value = ''
  options.value = []
}
function initFuse(list) {
  fuse.value = new Fuse(list, {
    shouldSort: true,
    threshold: 0.4,
    location: 0,
    distance: 100,
    minMatchCharLength: 1,
    keys: [{
      name: 'title',
      weight: 0.7
    }, {
      name: 'path',
      weight: 0.3
    }]
  })
}

function getNormalPath(p) {
  if (!p || p === 'undefined') return '/'

  // 将连续的多个斜杠替换为一个
  let res = p.replace(/\/+/g, '/')

  // 移除结尾的斜杠，但保留根路径 '/'
  if (res.length > 1 && res.endsWith('/')) {
    res = res.slice(0, -1)
  }
  return res;
}

// Filter out the routes that can be displayed in the sidebar
// And generate the internationalized title
function generateRoutes(routes, basePath = '', prefixTitle = []) {
  let res = []

  for (const r of routes) {
    // skip hidden router
    if (r.hidden) { continue }
    const p = r.path.length > 0 && r.path[0] === '/' ? r.path : '/' + r.path;
    const data = {
      path: !isHttp(r.path) ? getNormalPath(basePath + p) : r.path,
      title: [...prefixTitle]
    }

    if (r.meta && r.meta.title) {
      data.title = [...data.title, r.meta.title]

      if (r.redirect !== 'noRedirect') {
        // only push the routes with title
        // special case: need to exclude parent router without redirect
        res.push(data)
      }
    }
    if (r.query) {
      data.query = r.query
    }

    // recursive child routes
    if (r.children) {
      const tempRoutes = generateRoutes(r.children, data.path, data.title)
      if (tempRoutes.length >= 1) {
        res = [...res, ...tempRoutes]
      }
    }
  }
  return res
}
function querySearch(query) {
  if (query !== '') {
    options.value = fuse.value.search(query)
  } else {
    options.value = []
  }
}

onMounted(() => {
  searchPool.value = generateRoutes(routes.value);
})

watchEffect(() => {
  searchPool.value = generateRoutes(routes.value)
})

watch(searchPool, (list) => {
  initFuse(list)
})
</script>

<style lang='scss' scoped>
.header-search-select {
  :deep(.el-select){

  }

  // 默认placeholder
  :deep(.el-select__placeholder.is-transparent) {
    color: #333333;
  }

  // 默认框状态样式更改
  :deep(.el-select__wrapper) {
    border-radius: 50px;
    background-color: #ffffff !important;
    padding: 0 18px;
    box-shadow: 0 0 0 1px #e6e6e6 inset !important;
    --el-select-focus-border-color: #e6e6e6 !important;
    --el-select-hover-border-color: #e6e6e6 !important;
  }

  // 修改下拉框样式-点击框focus
  :deep(.is-focus .el-input__wrapper) {
    box-shadow: 0 0 0 1px #e6e6e6 inset !important;
    --el-select-focus-border-color: #e6e6e6 !important;
    --el-select-hover-border-color: #e6e6e6 !important;
  }
}
</style>